using System;
using System.Web;
using System.Web.Caching;

using Azure.Infrastructure;

using Microsoft.WindowsAzure.StorageClient;

namespace Azure.Web
{
    public class CacheService<T> : ICache<T> where T : TableServiceEntity
    {
        private const string LatestKey = "__Latest_Post__";
        private readonly Cache _webCache;

        public CacheService()
        {
            _webCache = HttpRuntime.Cache;
        }

        public virtual T Latest
        {
            get { return (T) _webCache[LatestKey + typeof(T).Name]; }
            set { _webCache[LatestKey + typeof(T).Name] = value; }
        }

        public virtual T Get(string partitionKey, string rowkey)
        {
            return (T) _webCache.Get(GetKey(partitionKey, rowkey));
        }

        public void Add(T item)
        {
            _webCache.Add(GetKey(item), item, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
        }

        public virtual string GetKey(TableServiceEntity item)
        {
            return GetKey(item.PartitionKey, item.RowKey);
        }

        public virtual string GetKey(string partitionKey, string rowKey)
        {
            return String.Concat(partitionKey, rowKey).ToLowerInvariant();
        }
    }
}